package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.common.utils.RedisConstants.QUERY_SHOP_TYPE_LIST;
import static com.hmdp.common.utils.RedisConstants.QUERY_SHOP_TYPE_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
//        查缓存
        String json = stringRedisTemplate.opsForValue().get(QUERY_SHOP_TYPE_LIST);
        if (json != null) {
            try {
//        命中  返回  刷新有时效期
                Result result = new ObjectMapper().readValue(json, Result.class);
                stringRedisTemplate.expire(QUERY_SHOP_TYPE_LIST, QUERY_SHOP_TYPE_TTL, TimeUnit.MINUTES);
                return result;
            } catch (JsonProcessingException e) {
                log.error("缓存反序列化时出错，json:" + json);
            }
        }

//        未命中  查询  缓存  返回
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if (typeList == null) {
            return Result.fail("没有查询到该店铺。");
        }
        Result okResult = Result.ok(typeList);
        try {
            stringRedisTemplate.opsForValue().set(
                    QUERY_SHOP_TYPE_LIST,
                    new ObjectMapper().writeValueAsString(okResult),
                    QUERY_SHOP_TYPE_TTL,
                    TimeUnit.MINUTES);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return okResult;
    }
}
